package modelLayer;

import java.io.IOException;
import java.util.ArrayList;

import uiLayer.SaveToFile;
import controllerLayer.ProductCtr;

public class CustomerRecords {
	private static CustomerRecords instance = null;
	private ArrayList<Customer> customers;
	private ProductCtr pctr;
public CustomerRecords() {
		customers = new ArrayList<Customer>();
		pctr = new ProductCtr();
	}
public static CustomerRecords getInstance()       
{
	if(instance == null)
	{
		instance = new CustomerRecords();
	}
	return instance;
}
public void createCustomer(String id,String name, String address, String phoneNumber, double moneySpent, double discount) {
	Customer c1 = new Customer(id,name,address,phoneNumber,moneySpent,discount);
	customers.add(c1);
	
}

public ArrayList<Customer> getCustomers() {
	return customers;
}
public Customer getCustomer(String custID) {
		for(Customer cust: customers){
		if(cust.getId().equals(custID))return cust;
	}
	return null;
}

public String findCustomer(String ID){
	String c1 = "Customer doesn't exist";
	for(Customer cust: customers){
		if(cust.getId().equals(ID))c1 = cust.toString();
	}
	return c1;
}

public void updateCustomer(String Id,String address,String phoneNumber,double discount){
	Customer c1 = getCustomer(Id);
	if(!address.equals(""))c1.setAddress(address);
	if(!phoneNumber.equals(""))c1.setPhoneNumber(phoneNumber);
	if(discount!=0)c1.setDiscount(discount);
}
/*
 * This method adds bought items to ArrayList of bought items of one customer
 * it also sets money spent 
 */
public void buyItem(String ID,String name,double quantity,String id2, double discount){
	Customer c1 = getCustomer(ID);
	SaleLinesItem item = pctr.getSaleLinesItem(id2);
	double price = 0;
	if(item.getItemCollection()!=null)price=item.getPrice();
	else price= item.getProduct().getPrice();
	double total = price*quantity*discount;
	boolean stated = false;
	for(SaleLinesItem i1:c1.getItemsBought()){
		if(item.equals(i1)){
			stated = true;
			i1.setBuyQuantity(i1.getBuyQuantity()+quantity);
		}
	}	
	if(!stated){
		//item.getProduct().setQuantity(quantity);
		c1.addItemBought(item);
	}
	c1.setMoneySpent(c1.getMoneySpent()+ total);
	
	}

public void deleteCustomer(String Id){
	Customer c1 = getCustomer(Id);
	customers.remove(c1);
}
public void save() throws IOException{
	for(Customer c1: customers){
		SaveToFile.getInstance().save(c1.save());
}

}
}


